package org.zpengblog.cosdemo.controller;

import com.qcloud.cos.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.zpengblog.cosdemo.utils.CosUtil;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

/**
 * @author 林志鹏
 * @version 1.0.0
 * @date 2020/12/11 0:35
 */
@Controller
@Slf4j
public class IndexController {

    @Autowired
    private CosUtil cosUtil;

    @RequestMapping("/index")
    public ModelAndView index() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("index");
        return modelAndView;
    }

    @PostMapping("/upload")
    public String uploadFile(@RequestParam("file") MultipartFile file) throws Exception {
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
//a824b2df875e053dfdaaa7ce8a841e05
        PutObjectResult putObjectResult = cosUtil.fileUpload(inputStream, file.getOriginalFilename(), cosUtil.getCosKey());
        log.info("上传文件回调 【{}】", putObjectResult.getETag());
        return "success";
    }

    @RequestMapping("get")
    public void downLoad(HttpServletResponse response) throws Exception {
        InputStream in = cosUtil.download("tXo1BRCY9dae4o3fCD9RvZUN/WRNLwCxTyfIpJ3ofMY=");
        PrintWriter writer = response.getWriter();
        byte[] bytes = new byte[2048];
        int nRead;
        while ((nRead = in.read(bytes)) != -1) {
            ServletOutputStream outputStream = response.getOutputStream();
            outputStream.write(bytes);
        }

    }
}
